using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
//背包管理器ui
public class BagUIPage : MonoBehaviour
{
    public GameObject bagItemPrefab;
    public GameObject bagBgObj;
    public GameObject msgObg;
    public GameObject item { get; set; }
    //待使用的物品
    public ItemDatas_SO itemDatas_SO { get; set; }

    // Start is called before the first frame update
    void Start()
    {

    }
    void Awake()
    {
    }
    // Update is called once per frame
    void Update()
    {

    }
    void OnEnable()
    {
        setBagItems();
        setMsg();
        ClearAllKuang();
    }


    //逻辑层
    public void setBagItems()
    {
        foreach (Transform item in bagBgObj.transform)
        {
            Transform Item = item.Find("bagItemUI(Clone)");
            if (Item) Destroy(Item.gameObject);
        }
        for (int i = 0; i < GameManager.Instance.bag.Count; i++)
        {
            ItemDatas_SO ItemData = GameManager.Instance.bag[i];
            if (ItemData == null) return;
            //实例化item到bag_bg里的框里面
            GameObject ItemObject = Instantiate(bagItemPrefab, bagBgObj.transform.GetChild(i), false);
            ItemObject.transform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
            ItemObject.GetComponent<ItemDataView>().itemDatas_SO = ItemData;
            ItemObject.GetComponent<ItemDataView>().uiPage = gameObject;
            ItemObject.GetComponent<ItemDataView>().bagBgObj = bagBgObj;
            ItemObject.GetComponent<ItemDataView>().msgObj = msgObg;
            ItemObject.GetComponent<ItemDataView>().Init(ItemData);
        }
    }
    //ui层
    public void ClearAllKuang()
    {
        foreach (Transform item in bagBgObj.transform)
        {
            item.Find("kuang").gameObject.SetActive(false);
        }
    }
    public void setMsg()
    {
        if (msgObg == null) Debug.Log("未初始化msgObg");
        msgObg.transform.Find("itemName").GetComponent<TextMeshProUGUI>().text = "";
        msgObg.transform.Find("itemMsg").GetComponent<TextMeshProUGUI>().text = "选择物品";
        msgObg.transform.Find("num").GetComponent<TextMeshProUGUI>().text = "";
        msgObg.transform.Find("removeItemBtn").gameObject.SetActive(false);
        msgObg.transform.Find("useItemBtn").gameObject.SetActive(false);

    }

    //点击使用按钮使用物品
    public void UseItem()
    {
        if (itemDatas_SO.itemId == 1)
        {
            //设置角色属性
            GameManager.Instance.Player.GetComponent<DataController>().SetPlayerSpeedData(itemDatas_SO);
        }
        //用掉的物品直接从背包删除
        RemoveItem();
    }
    //从背包删除物品
    public void RemoveItem()
    {

        //删除物品
        GameManager.Instance.ReItem(itemDatas_SO);
        refreshPage();

    }
    //刷新界面
    void refreshPage()
    {
        //刷新界面
        itemDatas_SO = null;
        setBagItems();
        ClearAllKuang();
        setMsg();
    }
}
